﻿using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using OSharp.Extensions;
using OSharp.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 


namespace SMSSendTest
{
    public static class MasSmsService
    {
        private static readonly string apiUrl = "http://api.ums86.com:8899/sms/Api/Send.do";

       

        
        public static string GetMd5Hash(string input)
        {
            using (MD5CryptoServiceProvider md5Hash = new MD5CryptoServiceProvider())
            {
                // 计算字符串的哈希值  
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // 创建一个StringBuilder来收集字节  
                // 并创建字符串（十六进制格式）  
                StringBuilder sBuilder = new StringBuilder();

                // 循环遍历哈希数据的每个字节  
                // 并格式化为十六进制字符串  
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                // 返回十六进制字符串  
                return sBuilder.ToString();
            }
        }


        public static SendBatchSmsResponseBody SendSmsAsync(string phoneStr,string signStr, List<string> templateParams=null,string templateCode=null)
        {
           
            try
            {
                string ecName= "新巴尔虎左旗鑫泰基础设施投资有限责任公司", accessId= "nmzqapi"
                    , accessSecret= "e9*S6a9#",  content= "哈哈哈，这是测试短信",
                     addSerial="";
                var httpUrl = "https://mas.10086.cn/sms/norsubmit";
                var client = new RestClient(httpUrl);
                var request = new RestRequest();
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/json");

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(ecName);
                stringBuilder.Append(accessId);
                stringBuilder.Append(accessSecret);
                stringBuilder.Append(phoneStr);
                stringBuilder.Append(content);
                stringBuilder.Append(signStr);
                stringBuilder.Append(addSerial);

                string mac = GetMd5Hash(stringBuilder.ToString());

                var submit = new
                {
                    ecName = ecName,
                    apId = accessId,
                    mobiles = phoneStr,
                    content = content,
                    sign = signStr,
                    addSerial = addSerial,
                    mac = mac
                };
                string reqStr = submit.ToString().ToBase64String();

                request.AddParameter("application/json", reqStr, ParameterType.RequestBody);
                var reSend = client.Execute(request);

                var biz = new SendBatchSmsResponseBody();
                JObject jo = JsonConvert.DeserializeObject<JObject>(reSend.Content);
                if (reSend.StatusCode == HttpStatusCode.OK && jo.Property("success") != null && Convert.ToBoolean(jo["success"]))
                {
                    biz.Code = "ok";
                    biz.BizId = jo["msgGroup"].ToString();
                    biz.Message = "OK";
                }
                else
                {
                    biz.Code = reSend.ErrorMessage;
                    biz.BizId = "";
                    biz.Message = reSend.ErrorMessage;
                    if (jo != null)
                    {
                        biz.Code = jo["rspcod"].ToString();
                        biz.Message = jo["rspccod"].ToString();
                    }

                } 
                //"162415331050747967^0"
                //162415331050747967^0
                //753916831051241861^0
                //"325712031053869790^0"   "2CAF3941-E004-50E6-8029-FECCD72CAD36"
                return null;
                
            }
            catch (Exception error)
            {
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            return null;
             
        }

        private static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static string SendContent(string ecName, string accessId, string accessSecret, string sign, string addSerial, string phone, string content)
        {
            try
            {
                
                var httpUrl = "http://112.35.1.155:1992/sms/norsubmit";

                var para = new MasCloudPara()
                {
                    ecName = ecName,
                    apId = accessId,
                    mobiles = phone,
                    content = content,
                    sign = sign,
                    addSerial = addSerial,                   
                };

                try
                {
                    para.mac = GetMd5Hash(para.ecName + para.apId + accessSecret + para.mobiles + para.content + para.sign + para.addSerial);
                    string json = JsonConvert.SerializeObject(para);
                    if(string.IsNullOrEmpty(json))
                    {
                        return "";
                    }
                    var requestContent = json.ToBase64String();
                   
                    var client = new RestClient(httpUrl);
                    var request = new RestRequest();
                    request.Method = Method.Post;
                    request.AddHeader("Content-Type", "application/json");
                    request.AddParameter("application/json", requestContent, ParameterType.RequestBody);

                   
                    var reSend = client.Execute(request);



                    return reSend.Content;
                    /*
                    if (masCloudResponse.success)
                    {
                        Console.WriteLine("发送成功");
                    }
                    else
                    {
                        Console.WriteLine("发送失败" + masCloudResponse.rspcod);
                    }
                    */
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return null;

 
 

            }
            catch (Exception error)
            {
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            return null;

        }

        public static bool SendSms(String mobiles, StringBuilder paramss, String templateId)
        {

            bool bRet = false;
            JObject jsonObj = new JObject();
            jsonObj.Add("ecName", "填短信平台的公司：南通最牛逼的有限公司");
            jsonObj.Add("apId", "attend");
            jsonObj.Add("templateId", templateId);
            jsonObj.Add("mobiles", mobiles);
            jsonObj.Add("params", paramss.ToString());
            jsonObj.Add("sign", "这里是短信接口签名pwa4T");
            jsonObj.Add("addSerial", "");

            StringBuilder sbFormatString = new StringBuilder();
            sbFormatString.Append("{0}{1}{2}{3}{4}{5}{6}");

            jsonObj.Add("mac", GetMd5Hash(String.Format(sbFormatString.ToString(), "填短信平台的公司：南通最牛逼的有限公司", "attend", "短信接口的密码!@#$",
                templateId, mobiles, paramss.ToString(), "这里是短信接口签名pwa4T", "")));
            //这边要注意base64加密，否则报错
            /*
            string _data = Base64Encode(Encoding.UTF8, jsonObj.ToString());
            JObject rejsonObj = null;
            try
            {
                String sResult = HttpWebRequestHelper.GetDatahttps(_data, "https://问客服MM要地址/sms/tmpsubmit");
                rejsonObj = JObject.Parse(sResult);
                Console.WriteLine(rejsonObj.ToString());
                if ("success".Equals(rejsonObj.GetValue("rspcod").ToString()))
                {
                    bRet = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XFRemoteService 接口调用:ERROR => " + ex.Message);
            }
            */
            return bRet;
        } 
    }
}
